﻿using System;
using System.Web;
using System.Reflection;
using System.Collections.Generic;
using Newtonsoft.Json;
using Intorise.Library.Common;

public class CommonHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
    static object locker = new object();
    static Dictionary<string, MethodInfo> methodDict = new Dictionary<string, MethodInfo>();
    protected HttpContext context = null;

    public void ProcessRequest(HttpContext context)
    {
        this.context = context;
        context.Response.ContentType = "text/json";
        if (context.Request.QueryString.Count == 0 || context.Request.QueryString.Keys[0].ToLower() != "method")
        {
            WriteResultJson(false, "method必须是第一个参数！"); return;
        }
        String methodName = context.Request.QueryString["method"];
        if (string.IsNullOrEmpty(methodName))
        {
            return;
        }
        string ticket = context.Request["ticket"];
        if (ticket != "5234108899")
        {
            WriteResultJson(false, "ticket错误！"); return;
        }

        Type type = this.GetType();
        System.Reflection.MethodInfo method = null;
        if (!methodDict.ContainsKey(methodName))
        {
            lock (locker)
            {
                if (!methodDict.ContainsKey(methodName))
                {
                    method = type.GetMethod(methodName);
                    if (method == null)
                    {
                        WriteResultJson(false, "没有找到方法：" + methodName);
                        return;
                    }
                    methodDict.Add(methodName, method);
                }
            }
        }

        method = methodDict[methodName];
        if (method == null)
        {
            WriteResultJson(false, "没有找到方法：" + methodName);
            return;
        }

        try
        {
            method.Invoke(this, null);
        }
        catch (Exception ex)
        {
            WriteExceptionJson(ex);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    #region write json method
    protected void WriteSuccessJson(string message = null)
    {
        HttpContext.Current.Response.Write(JsonConvert.SerializeObject(new { Success = true, Message = message }));
    }

    protected void WriteScriptBlock(string scripts)
    {
        context.Response.ContentType = "text/html";
        context.Response.Write("<script type='text/javascript'>window.onload=function(){" + scripts + "}</script>");
    }

    protected void WriteResultJson(bool success, string message = null)
    {
        if (!success)
        {
        }

        HttpContext.Current.Response.Write(JsonConvert.SerializeObject(new { Success = success, Message = message }));
    }

    protected void WriteSubmitInvalidaDataJson()
    {
        WriteResultJson(false, "提交的数据错误！");
    }

    protected void WriteExceptionJson(Exception ex)
    {
        WriteResultJson(false, "操作时出现错误" + "<br>" + ex.Message);
        Logs.HandleException(ex);

        int count = 0;
        while (ex.InnerException != null && count++ < 3)
        {
            Logs.HandleException(ex.InnerException);
        }
    }

    protected void WriteResultJson(object entity, JsonSerializerSettings settings = null)
    {
        if (settings == null)
        {
            try
            {
                //  string jsonString = JsonHelper.JsonSerializer<SysUser>((SysUser)entity);
                HttpContext.Current.Response.Write(JsonConvert.SerializeObject(entity));
            }
            catch (Exception ex)
            {
                Logs.HandleException(ex.InnerException);
            }
        }
        else
        {
            HttpContext.Current.Response.Write(JsonConvert.SerializeObject(entity, settings));
        }
    }
    #endregion
}